# coding:utf-8
import configparser
import os
import re
from io import BytesIO

import requests
from PIL import Image

user_pswd_cfg = os.environ['user_pswd']
cf = configparser.ConfigParser()
cf.read(user_pswd_cfg, encoding="utf-8")
renren_user = cf.get('renren', 'renren_user')
renren_pswd = cf.get('renren', 'renren_pswd')


class RequestDemo:
    def _test_get_direct(self):
        """
        rd = RequestDemo()
        rd._test_get_direct()
        """
        # 直接调用get方法
        response = requests.get('http://www.baidu.com')
        print("get请求的结果: ", response)

    def _test_get_headers_params(self):
        """
        rd = RequestDemo()
        rd._test_get_headers_params()
        """
        # 添加headers和查询参数
        kw = {'wd', '上海'}
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, '
                                 'like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
        response = requests.get('http://www.baidu.com/', params=kw, headers=headers)
        print('get请求unicode格式数据: ', response.text)
        print('get请求二进制格式数据: ', response.content)
        print('get请求完整的url: ', response.url)
        print('get请求头部字节编码: ', response.encoding)
        print('get请求响应码: ', response.status_code)

    def _test_get_proxy(self):
        """
        rd = RequestDemo()
        rd._test_get_proxy()
        """
        # 使用代理
        # 根据协议类型，选择不同的代理
        proxies = {
            "http": "http://221.2.155.35:8060",
            "https": "http://114.91.164.97:9999",
        }
        response = requests.get('http://www.baidu.com/', proxies=proxies)
        print('get请求代理响应文本内容: ', response.text)

    def _test_get_proxy_secret(self):
        """
        rd = RequestDemo()
        rd._test_get_proxy_secret()
        """
        # 私密代理
        # TODO 使用私密代理没有返回数据
        proxy = {"http": "mr_mao_hacker:sffqry9r@61.158.163.130:16816"}
        response = requests.get("http://www.baidu.com", proxies=proxy)
        print(response.text)

    def _test_get_auth(self):
        """
        rd = RequestDemo()
        rd._test_get_auth()
        """
        # web客户端验证
        auth = ('test', '123456')
        response = requests.get('http://api.github.com/user', auth=auth)
        print(response.text)

    def _test_get_response_request(self):
        """
        rd = RequestDemo()
        rd._test_get_response_request()
        """
        # 获取新浪首页
        response = requests.get('http://www.sina.com')
        print('get请求头: ', response.request.headers)
        print('get请求内容猜测解压功能: ', response.text)
        print('get请求内容自带解压功能: ', response.content.decode())

    def _test_get_bytesio(self):
        """
        rd = RequestDemo()
        rd._test_get_bytesio()
        """
        # 获取网络上图片的大小
        img_url = "http://imglf1.ph.126.net/pWRxzh6FRrG2qVL3JBvrDg==/6630172763234505196.png"
        response = requests.get(img_url)
        f = BytesIO(response.content)
        img = Image.open(f)
        print(img.size)

    def _test_get_cookies(self):
        """
        rd = RequestDemo()
        rd._test_get_cookies()
        """
        response = requests.get('http://www.baidu.com/')
        cookiejar = response.cookies
        cookiedict = requests.utils.dict_from_cookiejar(cookiejar)
        cookie = requests.utils.cookiejar_from_dict(cookiedict, cookiejar)
        print(cookiejar)
        print(type(cookiedict))
        print(cookie)
        print('cookiejar内容: ', cookiejar)
        print('cookiedict内容: ', cookiedict)
        print('cookie内容：', cookie)

    def _test_get_cookies_update(self):
        """
        rd = RequestDemo()
        rd._test_get_cookies_update()
        """
        url = 'http://www.renren.com/923768535'
        headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/"
                          "61.0.3163.100 Safari/537.36",
        }
        temp = "anonymid=jo3r4dao2f8hf; _r01_=1; _de=07F5129AC246F2285259CA86A67F74DE; ln_uact=15251847740; ln_hurl=http://head.xiaonei.com/photos/0/0/men_main.gif; jebe_key=cfa0dc0e-1d10-4d46-a73f-3c17a0d9728c%7C932cb64c4b2269f17d75e9016741092f%7C1541388978454%7C1%7C1541388984564; ap=960768847; depovince=JS; jebecookies=cefb79e6-a439-4eb3-9a81-1478509ba871|||||; JSESSIONID=abcj0n2YBOqRF8XbITZBw; ick_login=7109149f-2925-4fa0-92ca-56699243910a; p=14c122f644acf3a8e49c2688a82de8867; first_login_flag=1; t=3dd274940a083d5420a805ef884603147; societyguester=3dd274940a083d5420a805ef884603147; id=960768847; xnsid=c49b997; loginfrom=syshome; wp_fold=0; jebe_key=cfa0dc0e-1d10-4d46-a73f-3c17a0d9728c%7C932cb64c4b2269f17d75e9016741092f%7C1541388978454%7C1%7C1541687108719"

        cookies = {}
        for item in temp.split('; '):
            key, value = item.split('=')
            cookies[key] = value
        print(cookies)

        # 发起请求
        response = requests.get(url, headers=headers, cookies=cookies)
        with open('./ext/cRequest/renren.html', 'wb')as f:
            f.write(response.content)
        # 验证是否登录成功
        print(re.findall('李震', response.content.decode()))

    def _test_get_session(self):
        """
        rd = RequestDemo()
        rd._test_get_session()
        """
        # 实现人人网登录
        ssion = requests.session()
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.284"
                          "0.99 Safari/537.36"
        }
        data = {"email": renren_user, "password": renren_pswd}
        ssion.post("http://www.renren.com/PLogin.do", data=data)
        response = ssion.get("http://www.renren.com/960768847/profile")
        print('session读取打印内容: ', response.text)

    def _test_get_verify(self):
        """
        rd = RequestDemo()
        rd._test_get_verify()
        """
        # 处理http请求SSL证书验证
        response = requests.get("http://www.baidu.com/", verify=True)
        print('请求SSL证书: ', response.text)
        try:
            response = requests.get("https://www.12306.cn/mormhweb/")
        except Exception as e:
            print('12306测试请求SSL证书: ', e)

        response = requests.get("https://www.12306.cn/mormhweb/", verify=False)
        print('12306跳过SSL证书认证: ', response.text)

    def _test_get_timeout(self):
        """
        rd = RequestDemo()
        rd._test_get_timeout()
        """
        # 超时设定
        url = 'http://www.youtube.com'
        response = requests.get(url, timeout=3)
        print(response)

    def _test_post_direct(self):
        """
        rd = RequestDemo()
        rd._test_post_direct()
        """
        # 基本的post方法
        data = '呵呵'.encode()
        response = requests.post('http://www.baidu.com/', data=data)
        print('post请求的结果: ', response)

    def _test_post_data_youdao_translate(self):
        """
        rd = RequestDemo()
        rd._test_post_data_youdao_translate()
        """
        # 传入data数据
        # TODO  post请求访问被拒
        formdata = {
            "type": "AUTO",
            "i": "i love python",
            "doctype": "json",
            "xmlVersion": "1.8",
            "keyfrom": "fanyi.web",
            "ue": "UTF-8",
            "action": "FY_BY_ENTER",
            "typoResult": "true"
        }
        url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103"
                          " Safari/537.36"
        }
        response = requests.post(url, data=formdata, headers=headers)
        print('post请求的响应文本: ', response.text)
        print('post请求的json文本: ', response.json())


if __name__ == '__main__':
    rd = RequestDemo()
    rd._test_get_cookies_update()
